// 振动统计，每5分钟1个（7+18字节）
define(function(require){
	var $ = require("jquery");
	var justep = require("$UI/system/lib/justep");
	var echarts = require("../lib/echarts/echarts-all-min");
	var mqtt = require("../mqttclient/mqtt-baidu");
	require("../lib/moment.min");

	var comm = require('../lib/user/comm');
	 
	
	var Model = function(){
		this.callParent();
		this.chart = null;
		this.chartDataZdnum = [];	// 统计周期内的振动次数
		this.chartDataZdmax = [];	// 统计周期内的振动振幅最大值，毫米
		this.chartDataZdfrq = [];	// 统计周期内的平均振动频率
		this.chartxAxis = [];		// chart 的  X 轴坐标点
		this.chartDataMax = 5;		// chart X方向最多数据个数； 1分钟 一个数据
		this.dataCounter = 0;       // 接收的数据个数
		this.chartHeight = justep.Bind.observable('200px');  // 默认 chart 高度
		
		this.timerChartRender = null;
	};

    Model.prototype.test = function() {
    	alert('test ok');
    };

	// 将数据保存到 this.chartData 中，并绘制 chart； buff=收到的 7+18字节数据包
	Model.prototype.doMsgArrivedAccelSTX = function (message) {
		//justep.Util.hint('accel st x data arrived');
		
		var vb = new Uint8Array(message.payloadBytes);
		var year = vb[0] + vb[1]*256;
		var time = moment([year, vb[2]-1, vb[3], vb[4], vb[5], vb[6], 0]); // 初始化是月从0开始；0=1月
		
		var zdnum = vb[7] + vb[8]*256;	           // 振动次数
		var zdmax = (vb[9] + vb[10]*256) / 10;     // 振动振幅最大值，毫米;
		var zdfrq = (vb[11] + vb[12]*256) / 1000;  // 振动平均频率： Hz 
		var timestr = moment(time).format('HH:mm');

		this.dataAppend(timestr, zdnum, zdmax, zdfrq)
	    this.dataRender();
    };


	// 将数据保存到 this.chartData 中；timestr=x轴; val=y轴
    Model.prototype.dataAppend = function(timestr, zdnum, zdmax, zdfrq) {
    	
    	if(this.dataCounter === 0) {
    		this.chartxAxis.splice(0, this.chartxAxis.length); //清空数组 
    		this.chartDataZdnum.splice(0, this.chartDataZdnum.length); //清空数组 
    		this.chartDataZdmax.splice(0, this.chartDataZdmax.length); //清空数组 
    		this.chartDataZdfrq.splice(0, this.chartDataZdfrq.length); //清空数组 
    		
    		for (var i=0; i<this.chartDataMax; i++) {
    			this.chartxAxis.push(' ');
    			this.chartDataZdnum.push(0);
    			this.chartDataZdmax.push(0);
    			this.chartDataZdfrq.push(0);
    		}
    	}
    	
    	if (this.dataCounter < this.chartDataMax) {
    		this.chartxAxis[this.dataCounter] = timestr;
    		this.chartDataZdnum[this.dataCounter] = zdnum;
    		this.chartDataZdmax[this.dataCounter] = zdmax;
    		this.chartDataZdfrq[this.dataCounter] = zdfrq;
    	} else {
	    	while(this.chartDataZdnum.length >= this.chartDataMax) {
	    		this.chartxAxis.shift();
	    		this.chartDataZdnum.shift();
	    		this.chartDataZdmax.shift();
	    		this.chartDataZdfrq.shift();
	    	}
	    	
	    	this.chartxAxis.push(timestr);
	        this.chartDataZdnum.push(zdnum);
	        this.chartDataZdmax.push(zdmax);
	        this.chartDataZdfrq.push(zdfrq);
    	}
 	
        this.dataCounter = this.dataCounter + 1;
    	//return data;
    };
    
	// 在 chart 上绘制 this.chartData 数据
    Model.prototype.dataRender = function() {
	    this.chart.setOption({
	    	xAxis: [{data: this.chartxAxis}],
		    series: [
		        {
			        name: '次数',  // 振动次数
		        	data: this.chartDataZdnum
		        },
		        {
			        name: '振幅',  // 最大振幅
		        	data: this.chartDataZdmax
		        },
		        {
			        name: '频率',  // 平均频率
		        	data: this.chartDataZdfrq
		        },
		    ],   
	    });
    };
    
    Model.prototype.chartInit = function(chartHeight) {
        var option = {
        	title: {
        		text: '振动统计',
        		left: '36px',
        		textStyle: {
        			fontSize: '14',
        		}
        	},
		    grid: {
		        left: '36px',        // 60px
		        right: '20px',       // 40px
		        top: '10px',
		        bottom: '20px',
		        containLabel: false
		    },
            legend: {
                data:['次数','振幅', '频率'],
                left: '96px',
        		textStyle: {
        			fontSize: '12'
        		}
            },
            toolbox: {
                show : true,
                feature : {
                    mark : {show: true},
                    dataView : {show: false, readOnly: false},
                    magicType : {show: false, type: ['line', 'bar']},
                    restore : {show: true},
                    saveAsImage : {show: true}
                }
            },

            tooltip : {
                trigger: 'axis'
            },
            
		    xAxis: [{
		        type: 'category',
		        data: [], 
		    }],
		    
		    yAxis: {
		        type: 'value',
		        scale: false,
		        //boundaryGap: [0, '100%'],
		        splitLine: {
		            show: false
		        },
		        nameTextStyle: {
		        	fontWeight: 'bold',
		        	fontSize: '16',
		        },
		    },
		    
		    series: [
		        {
			        name: '次数',
			        type: 'bar',
			        showSymbol: false,
			        hoverAnimation: false,
			        label:{ 
			        	normal:{ 
				        	show: true, 
				        	position: 'top',	// inside, top
			        	}, 
			        },
		        	data: this.chartDataZdnum
		        },
		        {
			        name: '振幅',
			        type: 'bar',
			        showSymbol: false,
			        hoverAnimation: false,
			        label:{ 
			        	normal:{ 
				        	show: true, 
				        	position: 'top',	// inside, top
			        	}, 
			        },
		        	data: this.chartDataZdmax
		        },
		        {
			        name: '频率',
			        type: 'bar',
			        showSymbol: false,
			        hoverAnimation: false,
			        label:{ 
			        	normal:{ 
				        	show: true, 
				        	position: 'top',	// inside, top
			        	}, 
			        },
		        	data: this.chartDataZdfrq
		        },
		    ],
            

            calculable : true,

        };
        
		this.chartHeight.set(chartHeight);
        this.chart = echarts.init(this.getElementByXid('pnlChart'));
        var myChart = this.chart;
        myChart.setOption(option);
    };
    
    Model.prototype.modelLoad = function(event) {
    	var ch;
    	if(this.params.chartHeight)
    	{
    		ch = this.params.chartHeight;
    	}
    	else
    	{
        	ch = (window.innerHeight * 0.28).toFixed() + 'px';
    	}
    	this.chartInit(ch);

        var self = this;
		mqtt.onMsgArrivedAccelSTX = function(message) { self.doMsgArrivedAccelSTX(message);};

		// 调试用，用 timer 模拟数据
//		var i = 1;
//		this.timerChartRender = setInterval(function () {
//			self.dataAppend(i++, 2, 1.6, 2.345);
//		    self.dataRender()
//		}, 1000);
		
    };
    
	Model.prototype.modelUnLoad = function(event){
		mqtt.unsubscribe(comm.gParams.baiduTopics.accelSTX + '/#');
	};
    
	return Model;
}
);